// 路由前置守卫文件
import router from '@/router'
import { useUserStore } from './stores/userStore'
import { ElMessage } from 'element-plus';
import { getProfileAPI } from './apis/user';
import type { RouteRecordRaw } from 'vue-router';
import { asyncRoutes } from './router/asyncRoutes';
import { useMenuStore } from './stores/menu';

// 白名单
const WHITE_LIST = ["/login", "/404"];

/**
 * 处理一级路由数据
 */
const getFirstRoutePerms = (permissions: string[]) => {
  const arr = permissions.map(item=>item.split(':')[0])
  return Array.from(new Set(arr))
}
// 处理二级路由权限数据
const getSecondRoutePerms = (permsArr: string[]) => {
  const newArr = permsArr.map(item => {
    const arr = item.split(':')
    return `${arr[0]}:${arr[1]}`
  })
  return [...new Set(newArr)]
}

// 处理路由数据 返回筛选和后的用户权限
const getRoutes = (
  firstRoutePerms: string[],  // 一级路由权限
  secondRoutePerms: string[], // 二级路由权限
  asyncRoutes: RouteRecordRaw[], // 所以动态路由表
) => {
    // 超级管理员，不做筛选，返回所有路由信息
    if(firstRoutePerms.includes('*')){
      return [...asyncRoutes]
    }
    // 根据一级和二级对动态路由表做过滤 return出去过滤之后的路由表
    // 1. 根据一级路由对动态路由表做过滤
    const firstRoutes = asyncRoutes.filter(item => {
      return firstRoutePerms.includes(item.meta!.permission!)
    })
    // console.log('筛选后的一级路由',firstRoutes)
    // 2. 根据二级路由对动态路由表做过滤
    const lastRoutes = firstRoutes.map(item=>{
      return {
        ...item,
        children: item.children?.filter(son =>{
          return secondRoutePerms.includes(son.meta!.permission!)
        })
      }
    })
    // console.log('lastRoutes',lastRoutes)
    return lastRoutes
}


// 路由前置守卫
router.beforeEach(async(to, from, next) => {
  const userStore = useUserStore()
  if(userStore.token){
  // 如果没有用户信息，发送请求获取，并保存到 store 中
    if(!userStore.profile.id){
      const res = await getProfileAPI()
      console.log('res',res)
      userStore.setProfile(res.data)
      const firstRoutePerms = getFirstRoutePerms(res.data.permissions)
      console.log('firstRoutePerms',firstRoutePerms)
      const secondRoutePerms = getSecondRoutePerms(res.data.permissions)
      console.log('secondRoutePerms',secondRoutePerms)
      
      const perRoutes = getRoutes(firstRoutePerms, secondRoutePerms, asyncRoutes)
      // 2. 遍历匹配的路由，动态添加到路由表中
      console.log('perRoutes',perRoutes)
      perRoutes.forEach(item => {
        router.addRoute(item as RouteRecordRaw)
      })

       // 3. 保存侧栏菜单路由
       const menuStore = useMenuStore()
       menuStore.setMenuList(perRoutes as RouteRecordRaw[])

      next({...to})
    }else{
      next()
    }
    
  }else {
  if(WHITE_LIST.includes(to.path)){
    next()
  }else{
    next("/login")
    ElMessage.warning("身份信息失效，请先登录")
  }
}
})